package com.njrsrc.android.tasks;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.njrsrc.android.bean.Image;
import com.njrsrc.android.bean.UserInfo;
import com.njrsrc.common.utils.UploadImage;

public class UploadPicTask extends AsyncTask<Object, Integer, Void> {
	private String url;
	private Handler registerHandler;
	private UserInfo registerInfo;
	private Map<String, String> requestMap;
	private String pic_url;

	@Override
	protected Void doInBackground(Object... params) {
		if (params.length < 4) {
			return null;
		}
		registerHandler = (Handler) params[0];
		url = (String) params[1];
		registerInfo = (UserInfo) params[2];
		requestMap = (HashMap<String, String>) params[3];
		
		pic_url = requestMap.get("pic");
		requestMap.remove("pic");
		
		File file = new File(pic_url);
		if(!file.exists())
		{
			return null;
		}
		Image image = new Image();
		image.fileName = file.getName();
		image.formName = "pic";
		image.length = file.length();
		image.path = pic_url;
		image.type = pic_url.substring(pic_url.lastIndexOf(".") + 1,pic_url.length());
		Image[] files = new Image[1];
      	files[0] = image;    

		String queryStr = UploadImage.getInstance().post(url, requestMap.entrySet(), files);

		JSONObject jsonObject = null;
		
		Message msg = registerHandler.obtainMessage();
		if(queryStr == null || queryStr.trim().length() == 0)
		{
			msg.what = 7;
			registerHandler.sendMessage(msg);
			return null;
		}
		try {
			jsonObject = new JSONObject(queryStr);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		if (jsonObject != null) {
			try {
				if (jsonObject.toString().contains("error_code")) {
					// 返回错误
					registerInfo.setError_code(jsonObject.getString("error_code"));
					registerInfo.setError_message(jsonObject.getString("error_message"));
					msg.what = 7;
				} else {
					registerInfo.setUser_id(jsonObject.getString("user_id"));
					registerInfo.setPic_url(jsonObject.getString("pic_url"));
					msg.what = 6;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			registerHandler.sendMessage(msg);
		}
		return null;
	}
}